import 'dart:io';

import 'package:starkylin_file_shared/src/utils/general.dart';

class SocketClient {
  WebSocket? clientSocket; //客户端socket
  bool isConnected = false;

  //客户端建立连接
  Future<void> clientConnect(String ip, int port,
      {bool isWss = false, void Function(dynamic)? handler}) async {
    //客户端连接到服务端
    int retryCount = 0;
    const maxRetries = 10; // 设置最大重试次数

    while (!isConnected && retryCount < maxRetries) {
      try {
        clientSocket =
            await WebSocket.connect('${isWss ? 'wss' : 'ws'}://$ip:$port');
        isConnected = true;

        clientSocket!.listen(
          handler,
          onError: (error) {
            log('Error: $error');
          },
          onDone: () {
            isConnected = false;
          },
        );
      } catch (e) {
        retryCount++;
        await Future.delayed(const Duration(seconds: 1));
      }
    }

    if (!isConnected) {
      print('达到最大重试次数，无法连接到服务器');
    }
  }

  //客户端发送消息
  void clientSendMsg(String msg) {
    if (clientSocket == null) {
      return;
    }
    clientSocket!.add(msg);
  }

  void handleDone() {
    clientSocket?.close();
  }
}
